package com.zhongying.jf.util;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.nio.charset.Charset;

/**
 * @author liyuxuan
 * @Description
 * @Email liyuxuan@chinazyjr.com
 * Created on 2018/2/22 19:02
 * Copyright (c) 2018 All Rights Reserved.
 */
public class PDFUtil {

    public static InputStream htmlToPdf(String html){
        byte[] htmlBytes = null;
        try {
            htmlBytes = html.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream outputStream = null;
        Document document = new Document();
        PdfWriter writer = null;
        try {
            outputStream = new ByteArrayOutputStream(htmlBytes.length);
            writer = PdfWriter.getInstance(document, outputStream);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        document.open();

        try {
            // 使用我们的字体提供器，并将其设置为unicode字体样式
            MyFontsProvider fontProvider = new MyFontsProvider();
            fontProvider.addFontSubstitute("lowagie", "garamond");
            fontProvider.setUseUnicode(true);

            XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes("UTF-8")) , Charset.forName("UTF-8"), fontProvider);
        } catch (Exception e) {
            e.printStackTrace();
        }
        document.close();

        return new ByteArrayInputStream(outputStream.toByteArray());
    }

    /**
     * 重写 字符设置方法，解决中文乱码问题
     *
     */
    private static class MyFontsProvider extends XMLWorkerFontProvider {

        public MyFontsProvider(){
            super(null, null);
        }

        @Override
        public Font getFont(final String fontname, String encoding, float size, final int style) {
            BaseFont baseFont = null;
            try {
                baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
            } catch (DocumentException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Font font = new Font(baseFont);
            return font;
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println(FileUtils.readFileToByteArray(new File("d:/1baozhengdanbaohan.html")).length);
            InputStream inputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(new File("d:/1baozhengdanbaohan.html")));
            FileUtils.copyToFile(inputStream, new File("d:/b.pdf"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
